package com.marui.ch1.syn;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示重入锁（一个线程在外层获得锁后，在进入内层方法可以自动获取锁）
 * @author marui
 * @date 18:08 2020/4/11
 * @since 1.0
 */
public class ReenterLockDemo {

    private Lock lock = new ReentrantLock();

    public synchronized void methodA(){
        System.out.println(Thread.currentThread().getName()+" 执行methodA");
        methodB();
    }

    public synchronized void methodB(){
        System.out.println(Thread.currentThread().getName()+" 执行methodB");
    }

    public void methodC(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 执行methodC");
            methodD();
        } finally {
            lock.unlock();
        }
    }

    public void methodD(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 执行methodD");
        } finally {
            lock.unlock();
        }

    }


    public static void main(String[] args) {

        ReenterLockDemo lockDemo = new ReenterLockDemo();

        for (int i = 0; i < 4; i++) {
            new Thread(()->{
               // lockDemo.methodA();
                lockDemo.methodC();
            },"线程"+i).start();
        }
    }

}
